package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacade "github.com/hulutech-web/http_result"
	"goravel/app/http/requests"
	"goravel/app/models"
)

type DepartmentController struct {
	//Dependent services
}

func NewDepartmentController() *DepartmentController {
	return &DepartmentController{
		//Inject services
	}
}

// 必须上传站点的sid
func (r *DepartmentController) GateSite(ctx http.Context) (int, bool) {
	site_id := ctx.Request().RouteInt("sid")
	if site_id == 0 {
		return site_id, false
	}
	return site_id, true
}

// Index returns the department list.
// @Summary Get department
// @Description 部门列表.
// @Tags DepartmentController
// @Security BearerAuth
// @Accept json
// @Produce json
// @Id DepartmentList
// @Param Authorization header string true "Bearer token"
// @Success 200 {object} common.SuccessResponse "Successfully retrieved Menus ."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID DepartmentIndex
// @Router /api/admin/sid/{sid}/department/list [get]
func (r *DepartmentController) List(ctx http.Context) http.Response {
	sid, ok := r.GateSite(ctx)
	if ok == false {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "", "未选择站点")
	}
	departments := []models.Department{}
	facades.Orm().Query().Model(&models.Department{}).Where("site_id=?", sid).Find(&departments)
	return httpfacade.NewResult(ctx).Success("", departments)
}

// Index returns the department list.
// @Summary Get department
// @Description 部门.
// @Tags DepartmentController
// @Security BearerAuth
// @Accept json
// @Produce json
// @Id DepartmentIndex
// @Param Authorization header string true "Bearer token"
// @Success 200 {object} common.SuccessResponse "Successfully retrieved Menus ."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID DepartmentIndex
// @Router /api/admin/sid/{sid}/department [get]
func (r *DepartmentController) Index(ctx http.Context) http.Response {
	sid, ok := r.GateSite(ctx)
	if ok == false {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "", "未选择站点")
	}
	departments := []models.Department{}
	queries := ctx.Request().Queries()
	res, err := httpfacade.NewResult(ctx).SearchByParams(queries, map[string]interface{}{
		"site_id": sid,
	}).ResultPagination(&departments)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "", err.Error())
	}
	return res
}

// Show 查看部门.
// @Summary Show department
// @Description 查看部门.
// @Tags DepartmentController
// @Security BearerAuth
// @Accept json
// @Produce json
// @Id DepartmentShow
// @Param Authorization header string true "Bearer token"
// @Param id path int true "department ID"
// @Success 200 {object} common.SuccessResponse "Successfully retrieved department."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID DepartmentShow
// @Router /api/admin/sid/{sid}/department/{id} [get]
func (r *DepartmentController) Show(ctx http.Context) http.Response {
	sid, ok := r.GateSite(ctx)
	if ok == false {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "", "未选择站点")
	}
	id := ctx.Request().RouteInt("id")
	department := models.Department{}
	if err := facades.Orm().Query().Model(&models.Department{}).Where("id=?", id).Where("site_id=?", sid).Find(&department); err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "部门不存在", err.Error())
	}
	return httpfacade.NewResult(ctx).Success("", department)
}

// Store 新增部门.
// @Summary store department
// @Description 新增部门.
// @Tags DepartmentController
// @Security BearerAuth
// @Accept json
// @Produce json
// @Param departmentData body requests.DepartmentRequest true "部门数据"
// @Id DepartmentStore
// @Param Authorization header string true "Bearer token"
// @Success 200 {object} common.SuccessResponse "Successfully retrieved Menus ."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID DepartmentStore
// @Router /api/admin/sid/{sid}/department [post]
func (r *DepartmentController) Store(ctx http.Context) http.Response {
	_, ok := r.GateSite(ctx)
	if ok == false {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "", "未选择站点")
	}
	department := models.Department{}
	var departmentRequest requests.DepartmentRequest
	errors, err := ctx.Request().ValidateRequest(&departmentRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	facades.Orm().Query().Model(&models.Department{}).Create(&models.Department{
		Pid:    departmentRequest.Pid,
		SiteID: departmentRequest.SiteID,
		Name:   departmentRequest.Name,
		Status: departmentRequest.Status,
		Remark: departmentRequest.Remark,
	})
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	return httpfacade.NewResult(ctx).Success("创建成功", department)
}

// Update 更新部门.
// @Summary update department
// @Description 新增部门.
// @Tags DepartmentController
// @Security BearerAuth
// @Accept json
// @Produce json
// @Param departmentData body requests.DepartmentRequest true "部门数据"
// @Id DepartmentUpdate
// @Param Authorization header string true "Bearer token"
// @Param id path int true "department ID"
// @Success 200 {object} common.SuccessResponse "Successfully retrieved Menus ."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID DepartmentUpdate
// @Router /api/admin/sid/{sid}/department/{id} [put]
func (r *DepartmentController) Update(ctx http.Context) http.Response {
	_, ok := r.GateSite(ctx)
	if ok == false {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "", "未选择站点")
	}
	id := ctx.Request().RouteInt("id")
	department := models.Department{}
	var departmentRequest requests.DepartmentRequest
	errors, err := ctx.Request().ValidateRequest(&departmentRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	var user models.User
	facades.Auth(ctx).User(&user)
	if _, err := facades.Orm().Query().Model(&models.Department{}).Where("id=?", id).Update(models.Department{
		Pid:    departmentRequest.Pid,
		SiteID: departmentRequest.SiteID,
		Name:   departmentRequest.Name,
		Status: departmentRequest.Status,
		Remark: departmentRequest.Remark,
	}); err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "更新失败", err.Error())
	}
	return httpfacade.NewResult(ctx).Success("修改成功", department)
}

// Destroy 删除部门.
// @Summary delete department
// @Description 查看部门.
// @Tags DepartmentController
// @Security BearerAuth
// @Accept json
// @Produce json
// @Id DepartmentDestroy
// @Param Authorization header string true "Bearer token"
// @Param id path int true "department ID"
// @Success 200 {object} common.SuccessResponse "Successfully retrieved Menus ."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID DepartmentDestroy
// @Router /api/admin/sid/{sid}/department/{id} [delete]
func (r *DepartmentController) Destroy(ctx http.Context) http.Response {
	_, ok := r.GateSite(ctx)
	if ok == false {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "", "未选择站点")
	}
	id := ctx.Request().RouteInt("id")
	row, err := facades.Orm().Query().Model(&models.Department{}).Where("id=?", id).Delete(&models.Department{}, id)
	if err != nil || row.RowsAffected == 0 {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "删除失败", err.Error())
	}
	return httpfacade.NewResult(ctx).Success("删除成功", nil)
}
